package com.fox.oauthfirst.authserver.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.AuthorizationRequest;
import org.springframework.security.web.savedrequest.DefaultSavedRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

@Controller
@SessionAttributes({"authorizationRequest"})
@Slf4j
public class LoginController {


    @GetMapping("/oauth/login")
    public String login(Model model,HttpServletRequest request){
        log.info("login");
        model.addAttribute("loginProcessUrl","/oauth/confirm");
        request.getParameterMap().forEach((k,v)->log.info(k+":" +v));
        return  "base-login";
    }

    @RequestMapping("/oauth/confirm")
    public ModelAndView confirm(Map<String, Object> param, HttpSession session, HttpServletRequest request,Model model) throws UnsupportedEncodingException {
        DefaultSavedRequest req = (DefaultSavedRequest) session.getAttribute("SPRING_SECURITY_SAVED_REQUEST");
        req.getParameterMap().forEach((k,v)->log.info(k+":" +v[0]));
        ModelAndView view = new ModelAndView();
        view.setViewName("base-grant");
        view.addObject("scopeList",req.getParameterValues("scope")!=null?req.getParameterValues("scope")[0].split(","):"");
        String response_type = req.getParameterValues("response_type")[0];
        String uri = "/oauth/authorize?redirect_uri=" + URLEncoder.encode(req.getParameterValues("redirect_uri")[0],"UTF-8");
        view.addObject("action",  uri +"&response_type=" + response_type);
        view.addObject("clientId", req.getParameterValues("client_id")[0]);
        return  view;
    }
}
